from random import choice

from django.core.mail import send_mail
from django.db.models import Q
from rest_framework import status, viewsets, mixins, permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework.response import Response
from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet

from Apps.Profile.utils.jwt_auth import create_token
from Apps.Profile.utils.filters import UserFilter
from Echo_Web import settings
from .serializers import *
from Apps.Profile.utils.pagination import UsersPagination
from Apps.utils.authentication import AccessAuthentication


class LoginViewSet(APIView):
    def post(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            pwd = request.data.get('password')
            user_object = User.objects.get(Q(username=username) | Q(mobile=username) | Q(email=username))
        except Exception:
            return Response({'code': 1, 'error': '用户名或密码错误'})
        if not user_object.check_password(pwd):
            return Response({'code': 2, 'error': '用户名或密码错误'})

        token = create_token({'id': user_object.id, 'name': user_object.username, 'sign': user_object.sign})
        return Response({'token': token, 'msg': 'success'})


class UserViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin,
                  viewsets.GenericViewSet):
    """
    用户注册和账户管理
    """
    serializer_class = UserRegSerializer
    queryset = User.objects.all()
    authentication_classes = (SessionAuthentication, AccessAuthentication,)

    # 动态设置序列化类
    def get_serializer_class(self):
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer
        return UserDetailSerializer

    # 动态设置permissions
    def get_permissions(self):
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            return []
        return []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(token, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()
        return create_token(serializer.data)

    def get_object(self):
        return self.request.user


class EmailCodeViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    发送短信验证码
    """
    serializer_class = EmailCheckSerializer

    def generate_code(self):
        """
        生成六位数字的验证码
        :return:
        """
        seeds = "1234567890"
        random_str = []
        for i in range(6):
            random_str.append(choice(seeds))

        return "".join(random_str)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        email = serializer.validated_data["email"]

        # 主题
        subject = 'CUIT实验室平台欢迎注册'
        code = self.generate_code()
        # message表示发送的纯文本，
        # 如果需要发送带样式的，则使用html_message
        # 用html_message时，message为空字符串
        message = "【CUIT实验室平台】您的验证码是{code}。如非本人操作，请忽略本条消息。".format(code=code)
        # 收件人列表
        receiver = [email]
        # 需要发送的带样式内容
        # html_message = '<h1>欢迎注册超级商城账号</h1>' \
        #                '请点击下面链接激活您的账号<br>'
        # 发送者
        sender = settings.EMAIL_FROM
        # 发送邮件
        sms_status = send_mail(subject, message, sender, receiver)
        print(sms_status)

        if sms_status != 1:
            return Response({
                "mobile": "发送失败"
            }, )
        else:
            code_record = EmailVerifyCode(code=code, email=email)
            code_record.save()
            return Response({
                "email": email
            }, status=status.HTTP_201_CREATED)


class ShowUserViewSet(ReadOnlyModelViewSet):
    queryset = User.objects.all().order_by('id')
    serializer_class = ShowUserSerializer
    pagination_class = UsersPagination
    filter_backends = (DjangoFilterBackend,)
    filter_class = UserFilter


class ProfileViewSet(ModelViewSet):
    queryset = User.objects.all().order_by('id')
    # serializer_class = UserSerializer
    authentication_classes = [AccessAuthentication, ]
